<template>
  <div class="page-container">
    <div class="in-container">
      <el-row :gutter="8" class="rowBox">
        <el-col :span="4">
          <companyTree
            :loading="company.loading"
            :treeData="company.treeData"
            :title="'公司信息'"
            @node-click="companyNodeClick($event)"
          />
        </el-col>
        <el-col :span="20">
          <AppTitleBox class="app-title-box" title="用户列表">
            <AppSearchForm @submit="search()" @reset="reset()">
              <el-form-item style="width: 200px">
                <el-tree-select
                  v-model="query.deptId"
                  clearable
                  value-key="id"
                  check-strictly
                  placeholder="请选择部门"
                  :data="dept.treeData"
                  :render-after-expand="false"
                >
                  <template #default="{ data }">
                    <el-option :label="data.name" :value="data.id" />
                  </template>
                </el-tree-select>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="query.name"
                  clearable
                  size="small"
                  placeholder="输入名称搜索"
                />
              </el-form-item>
              <el-form-item>
                <el-date-picker
                  v-model="query.date"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="query.enabled"
                  clearable
                  size="small"
                  placeholder="状态"
                  style="width: 90px"
                >
                  <el-option label="启用" :value="true" />
                  <el-option label="禁用" :value="false" />
                </el-select>
              </el-form-item>
            </AppSearchForm>

            <div style="margin-bottom: 8px">
              <el-button type="primary" @click="addUser"> 新增 </el-button>
            </div>
            <AppPageTable
              stripe
              :data="tableData.data"
              @change="getUserData()"
              :autostyle="'height: calc(100% - 64px);'"
              :option="tableData.option"
            >
              <el-table-column
                :show-overflow-tooltip="true"
                prop="username"
                label="账号"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="nickName"
                label="昵称"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="realName"
                label="姓名"
              />
              <el-table-column prop="gender" label="性别" width="50" />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="phone"
                label="电话"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                width="150"
                prop="company"
                label="公司"
              >
                <template #default="scope">
                  {{ scope.row.company ? scope.row.company.name : "" }}
                </template>
              </el-table-column>
              <el-table-column
                :show-overflow-tooltip="true"
                width="150"
                prop="email"
                label="邮箱"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="dept"
                label="部门"
              >
                <template #default="scope">
                  <div>{{ scope.row.dept ? scope.row.dept.name : "" }}</div>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" prop="enabled">
                <template #default="scope">
                  {{ scope.row.enabled ? "启用" : "禁用" }}
                </template>
              </el-table-column>
              <el-table-column
                :show-overflow-tooltip="true"
                prop="createTime"
                width="150"
                label="创建日期"
              />
              <el-table-column label="操作" width="160px" align="center">
                <template #default="scope">
                  <el-button
                    link
                    @click="updateUser(scope.row, scope.$index)"
                    type="primary"
                  >
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    @click="deleteUser(scope.row.id, scope.$index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    link
                    @click="openUpdateUserPwd(scope.row, scope.$index)"
                    type="primary"
                  >
                    修改密码
                  </el-button>
                </template>
              </el-table-column>
            </AppPageTable>
          </AppTitleBox>
        </el-col>
      </el-row>
    </div>
  </div>

  <userDialog
    ref="dialog"
    :companyTree="company.treeData"
    v-model:dialog="dialog"
    v-model:basicData="userBasicData"
    v-model:otherData="userOtherData"
    @submit="userSubmit"
  />

  <el-dialog v-model="pwdDialog.show" width="500px" title="修改密码">
    <el-form
      :model="pwdDialog.formData"
      :rules="pwdDialog.formRules"
      label-width="auto"
      ref="updatePwdRef"
    >
      <el-form-item label="新密码" prop="newPwd">
        <el-input
          v-model="pwdDialog.formData.newPwd"
          type="password"
          show-password
        >
        </el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input
          v-model="pwdDialog.formData.confirmPwd"
          type="password"
          show-password
        >
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button
          type="primary"
          @click="updatePwd"
          :loading="pwdDialog.btnLoading"
        >
          确定
        </el-button>
        <el-button link type="primary" @click="cancelUpdatePwd">
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent } from "vue";
import AppTitleBox from "@/components/AppTitleBox.vue";
import dayjs from "dayjs";
import userDialog from "./components/userDialog.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppSearchForm from "@/components/AppSearchForm.vue";
import companyTree from "./components/companyTree.vue";
import { encrypt } from "@/utils/rsaEncrypt.js";
export default defineComponent({
  components: {
    AppTitleBox,
    AppPageTable,
    AppSearchForm,
    companyTree,
    userDialog,
  },
  data() {
    return {
      //用户表格数据
      tableData: {
        data: [],
        option: useTableOption(),
      },
      //查询
      query: {
        name: "",
        date: [],
        enabled: "",
        deptId: "",
        companyId: "",
      },

      //用户表单基本数据
      userBasicData: {
        id: 0,
        username: "",
        phone: "",
        nickName: "",
        email: "",
        gender: "男",
        enabled: true,
        employeeAccount: "",
        phoneNumber: "",
        qq: "",
        realName: "",
        costLevel: 1,
        incomeLevel: 1,
      },
      //用户表单其他数据
      userOtherData: {
        //所属公司
        companyId: "",
        //所属部门
        deptId: "",
        jobs: [],
        roles: [],
      },

      dialog: {
        show: false,
        title: "",
      },

      //公司树
      company: {
        loading: false,
        treeData: [],
      },
      //部门树
      dept: {
        loading: false,
        treeData: [],
      },

      //修改密码弹窗
      pwdDialog: {
        show: false,
        btnLoading: false,
        formData: {
          id: "",
          newPwd: "",
          confirmPwd: "",
        },
        formRules: {
          newPwd: [
            { required: true, message: "请输入新密码", trigger: "change" },
          ],
          confirmPwd: [
            { required: true, message: "请输入确认密码", trigger: "change" },
          ],
        },
      },
    };
  },
  methods: {
    /**
     * 获取用户数据
     */
    getUserData() {
      let url = "/api/user/query";
      if (this.query.date && this.query.date.length > 0) {
        this.query.date[0] = dayjs(this.query.date[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.query.date[1] = dayjs(this.query.date[1])
          .add(1, "day")
          .subtract(1, "second")
          .format("YYYY-MM-DD HH:mm:ss");
        url =
          url +
          `?CreateTime=${this.query.date[0]}&CreateTime=${this.query.date[1]}`;
      }
      this.tableData.option.loading = true;
      this.$http
        .get(url, {
          PageIndex: this.tableData.option.page,
          PageSize: this.tableData.option.pageSize,
          KeyWords: this.query.name,
          Enabled: this.query.enabled,
          DeptId: this.query.deptId,
          CompanyId: this.query.companyId,
        })
        .then((res) => {
          this.tableData.data = res.content;
          this.tableData.option.total = res.totalElements;
          this.tableData.option.loading = false;
        });
    },
    search() {
      this.tableData.option.page = 1;
      this.getUserData();
    },
    reset() {
      this.query = {
        name: "",
        date: [],
        enabled: "",
        deptId: "",
        companyId: this.query.companyId,
      };
      this.getUserData();
    },
    addUser() {
      this.dialog.title = "新增用户";
      this.$refs.dialog.activeTab = "basicInfo";
      this.dialog.show = true;
    },
    updateUser(data, index) {
      this.dialog.title = "修改用户";
      this.$nextTick(() => {
        let userData = JSON.parse(JSON.stringify(data));
        const { companyId, deptId, jobs, roles } = userData;
        this.userBasicData = userData;
        this.userOtherData = { companyId, deptId, jobs, roles };
      });
      this.dialog.show = true;
    },
    deleteUser(id, index) {
      this.$http
        .post("/api/user/delete", {
          idArray: [id],
        })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.getUserData();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    async userSubmit() {
      let obj = {};
      await this.$refs.dialog.$refs.basicForm.validate((vaild) => {
        obj.basicInfo = vaild;
      });
      await this.$refs.dialog.$refs.otherForm.validate((vaild) => {
        obj.otherInfo = vaild;
      });
      if (obj.otherInfo && obj.basicInfo) {
        let url = "";
        let isCreate = false;
        if (this.userBasicData.id) {
          url = "/api/user/edit";
        } else {
          url = "/api/user/create";
          isCreate = true;
        }
        this.userBasicData.companyId = this.userOtherData.companyId;
        this.userBasicData.deptId = this.userOtherData.deptId;
        this.userBasicData.jobs = this.userOtherData.jobs.map((item) => {
          return {
            id: item.id,
            name: item.name,
          };
        });
        this.userBasicData.roles = this.userOtherData.roles.map((item) => {
          return {
            id: item.id,
            name: item.name,
          };
        });
        this.$http.post(url, this.userBasicData).then((res) => {
          if (res.status) {
            if (isCreate) {
              this.$message.success(res.message + " 默认密码123456");
            } else {
              this.$message.success(res.message);
            }
            this.getUserData();
            this.userCancel();
          } else {
            this.$message.error(res.message);
          }
        });
      } else {
        for (let i in obj) {
          if (obj[i] === false) {
            this.$refs.dialog.activeTab = i;
          }
        }
      }
    },
    userCancel() {
      this.dialog.show = false;
    },
    /**
     * 初始化公司树
     */
    initCompany() {
      this.company.loading = true;
      this.$http
        .get("/api/company/buildTree", {
          KeyWords: "",
        })
        .then((res) => {
          this.company.treeData = res;
        })
        .finally(() => (this.company.loading = false));
    },
    /**
     * 获取树节点
     * @param {object} node - 树节点
     */
    companyNodeClick(node) {
      if (node.id != this.query.companyId) {
        this.query.companyId = node.id;
        this.query.deptId = "";
        this.getDept(node.id);
        this.getUserData();
      }
    },
    /**
     * 点击公司节点获取部门树
     * @param {object} node - 公司id
     */
    getDept(id) {
      this.dept.loading = true;
      this.$http
        .get("/api/department/buildTree", {
          KeyWords: "",
          CompanyId: id,
        })
        .then((res) => {
          this.dept.treeData = res;
        })
        .finally(() => (this.dept.loading = false));
    },
    /**
     *  打开修改密码弹窗
     */
    openUpdateUserPwd(row) {
      this.pwdDialog.formData.id = row.id;
      this.pwdDialog.show = true;
    },
    /**
     * 确认修改密码弹窗
     */
    updatePwd() {
      this.$refs.updatePwdRef.validate((vaild) => {
        if (vaild) {
          this.pwdDialog.btnLoading = true;
          this.$http
            .post("/api/user/modify/password", {
              id: this.pwdDialog.formData.id,
              newPassword: encrypt(this.pwdDialog.formData.newPwd),
              confirmPassword: encrypt(this.pwdDialog.formData.confirmPwd),
            })
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message);
                this.pwdDialog.show = false;
              } else {
                this.$message.error(res.message);
              }
            })
            .finally(() => (this.pwdDialog.btnLoading = false));
        }
      });
    },
    /**
     * 取消修改密码弹窗
     */
    cancelUpdatePwd() {
      this.pwdDialog.show = false;
    },
  },
  watch: {
    "dialog.show"(newVal) {
      if (!newVal) {
        this.userBasicData = {
          id: 0,
          username: "",
          phone: "",
          nickName: "",
          email: "",
          gender: "男",
          enabled: true,
          employeeAccount: "",
          phoneNumber: "",
          qq: "",
          realName: "",
          CostLevel: 1,
          IncomeLevel: 1,
        };
        this.userOtherData = {
          //所属公司
          companyId: "",
          //所属部门
          deptId: "",
          jobs: [],
          roles: [],
        };
        this.$nextTick(() => {
          this.$refs.dialog.$refs.basicForm.resetFields();
          this.$refs.dialog.$refs.otherForm.resetFields();
        });
      }
    },
    "pwdDialog.show"(newVal) {
      if (!newVal) {
        this.$nextTick(() => {
          this.$refs.updatePwdRef.resetFields();
        });
      }
    },
  },
  mounted() {
    this.getUserData();

    this.initCompany();
  },
});
</script>

<style lang="scss" scoped>
.tree-node {
  width: 100%;
}

.rowBox {
  height: 100%;
  box-sizing: border-box;

  .el-col {
    height: 100%;
    box-sizing: border-box;
  }
}

.app-title-box {
  height: 100%;
  box-sizing: border-box;
}

.treeBox {
  height: 100%;
}

.table {
  height: calc(100% - 120px);
}

.table :deep(.tableHeader) th {
  background-color: #f7f8fa !important;
}

.searchForm .el-form-item {
  margin-bottom: 8px;
}

.dialogForm .el-form-item {
  width: 100%;
}

.dialogForm .el-select {
  width: 100%;
}

.dialogForm :deep(.el-input-number) {
  width: 100%;
}

.role-form {
  display: flex;
  // width: ;
  height: 400px;

  .form-left {
    width: 130px;
    height: 100%;

    // border: 1px solid grey;
    // border-radius: 4px;
    .form-item {
      width: 100%;
      height: 30px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 4px;

      :deep(.el-checkbox) {
        height: auto;
      }
    }

    .form-item:hover {
      color: var(--el-color-primary);
      border-color: var(--el-color-primary-light-7);
      background-color: var(--el-color-primary-light-9);
    }

    .form-item:active {
      color: #3a8ee6;
      border-color: #3a8ee6;
    }

    .form-item-active {
      color: #3a8ee6;
      border-color: #3a8ee6;
    }
  }

  .form-right {
    flex: 1;
    height: 100%;
    border-radius: 4px;
    border: 1px solid grey;
    margin-left: 8px;
  }
}
</style>
